package cn.com.fssg.platform.base.handler.impl.gsl.zw;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description: 工商联执委信息查询数据接口
 */
@Component
public class GslZwSelectCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();

//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        String zwId = jsonObject.getString("zw_id");
        String jcId = jsonObject.getString("jc_id");
        boolean isZw = BizUtil.cur().curUserRoleContain("002");
        if(isZw) {
            zwId = BizUtil.cur().curUserId();
            //执委登录，获取最新届次
            String queryJcSql = "select * from gsl_jc order by create_date desc";
            List<Map<String, Object>> jcList = jdbcTemplate.queryForList(queryJcSql, new HashMap<>());
            if(!jcList.isEmpty()) {
                jcId = jcList.get(0).get("id").toString();
            }
        }

        String sql = "SELECT i.id, i.name, i.company, i.sex, i.phone, i.nation, i.postal_address, i.birthday, i.name_of_agent, i.nationality, i.gent_account_number, i.native_place, i.position, i.birthplace, i.academic_degree, i.education, i.honekong_id, i.id_card, i.is_cadre, i.gsl_post, i.political_outlook, i.people_congress_post, i.cppcc_post, i.gsl_post_chose, i.social_position, i.no_post, i.model_worker, i.may_day_medal, i.red_flag_bearer, i.may_4t_medal, i.excellent_bbuilder, i.glory_medal, i.order_awards, i.no_social_honor, i.curriculum_vitae, i.update_by, i.update_date, i.create_by, i.create_date, i.del_flag, i.remarks, i.scope, i.card_id, i.people_congress_post_country, i.people_congress_post_province, i.people_congress_post_city, i.people_congress_post_county, i.cppcc_post_country, i.cppcc_post_province, i.cppcc_post_city, i.cppcc_post_county, i.gsl_post_chose_country, i.gsl_post_chose_province, i.gsl_post_chose_city, i.gsl_post_chose_county, i.zw_id, i.dl_card, i.sxzzbx, " +
                "q.id as qy_id, q.name_enterprise, q.legal_representative, q.enterprise_scale, q.credit_code, q.qy_scale, q.insurance_number, q.industry_classification, q.postcode, q.main_business, q.qyjy_registered_capital, q.qyjy_asset_load_ratio, q.qyjy_total_assets, q.qyjy_business_income, q.qyjy_net_assets, q.qyjy_total_profit, q.qyjy_tax_amount, q.zg_count, q.zg_labor_contract, q.zg_collective_contract, q.dzz_is_dzz, q.dzz_date, q.dzz_chose, q.dzz_count, q.labour_union, q.tzz_date, q.tzz, q.gysy, q.qy_characteristic, q.qy_info, q.five_year, q.sj_dzz_name, q.dzz_sj_name, q.dzz_job, q.yfzxsl_country, q.yfzxsl_province, q.yfzxsl_city, q.jkjbjsl_country, q.jkjbjsl_province, q.jkjbjsl_city, q.is_gxjsqy, q.patent_number, q.yffy, q.zjfs, q.dzzbzcy, q.dzzlxrxm, q.lxdh, q.zjtxqy_country, q.zjtxqy_province, q.yxgjqy, q.cylzqy, q.zzydxgjqy, q.cfwbqqy, q.ssgs, q.zgmywbqqy, q.gdbqmyqy, q.qsbqqy, q.bdltqy, q.gmysgyqy, q.qyjylytd, q.myqyrck " +
                "FROM gsl_zw_info i LEFT JOIN gsl_zw_qy q ON i.zw_id = q.zw_id " +
                "WHERE i.zw_id = :zw_id";
        Map<String, Object> param = new HashMap<>();
        param.put("zw_id", zwId);
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, param);
        if(!list.isEmpty()){
            Map<String, Object> map = list.get(0);
            map.put("jc_id", jcId);
            //解密姓名和手机号码
            String decName = decrypt((String) map.get("name"), "nametokon");
            String phone = decrypt((String) map.get("phone"), "ankon");
            map.put("name", decName);
            map.put("phone", phone);
            return map;
        }
        return new HashMap<>();
    }

    public static final String ALGORITHM = "AES";

    // 密钥补全
    public static byte[] padKey(byte[] key, int length) {
        return Arrays.copyOf(key, length);
    }

    /**
     * HEX 字符串转字节数组
     */
    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }

    /** 解密 */
    public static String decrypt(String input, String keys) throws Exception {
        // 1. HEX 字符串 → 字节数组
        byte[] cipherBytes = hexToBytes(input);
        byte[] keyBytes = padKey(keys.getBytes(StandardCharsets.UTF_8), 16);
        SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decrypted = cipher.doFinal(cipherBytes);
        return new String(decrypted, StandardCharsets.UTF_8);
    }
}